<?php
namespace app\crm\controller;

use app\common\controller\StoreBase;
use \PhpOffice\PhpSpreadsheet\IOFactory;

use think\facade\Db;
use app\crm\model\CrmContract;
use app\store\model\User;
use app\crm\model\CrmField;
use app\crm\model\CrmSetting;
use app\crm\model\CrmCustomer;
use app\crm\model\CrmTrack;
use app\store\model\DictData;
use app\store\model\Notice;

class Customer extends StoreBase
{
    /**
     * 用户列表
     * @return mixed
     */
    public function index()
    {
        //获取字段
        $field = CrmField::get_list();
        return $this->fetch('index',[
            'field'  => $field
        ]);
    }
    public function index_json($limit='15')
    {
        $model = new CrmCustomer();
        $param = $this->request->param();
        if(!empty($param['mobile'])){
            $model = $model->where('mobile',$param['mobile']);
        }
        if(!empty($param['name'])){
            $model = $model->where('name|company','like','%'.$param['name'].'%');
        }
        $list = $model->with(['user','category','from','industry'])->order('sort_order desc,id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 新增用户
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['store_id'] = StoreId();
            //检查是否有限制每日领取数量
            $data = crm_setting('crm');
            if(isset($data['crm_mobile']) && $data['crm_mobile'] == 1){
                //检查手机号码
                $is_mobile = Db::table('hq_crm_customer')->where(['store_id'=>StoreId(),'mobile'=>$param['mobile']])->find();
                if(isset($is_mobile)){
                    $this->success('该手机号码存在');
                }
            }

            $result = CrmCustomer::create($param);
            if ($result == true) {
                CrmTrack::insert_system_track($result->id,0,'添加了客户给'.User::get_username($param['user_id']));
                insert_user_log('添加了客户');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        //获取字段
        $field = CrmField::get_list();
        //分类
        $category = get_dict_list(13);
        $from = get_dict_list(14);
        $industry = get_dict_list(15);
        $status = CrmCustomer::get_status();
        $user = User::get_list();
        return $this->fetch('save', [
            'field'     => $field,
            'category'  => $category,
            'from'      => $from,
            'industry'  => $industry,
            'status'    => $status,
            'user'      => $user,
        ]);
    }

    /**
     * 修改用户
     * @param $id 编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //更新数据
            $resule = CrmCustomer::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                insert_user_log('修改了客户信息');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = CrmCustomer::where('id', $id)->find()?:$this->error('参数错误');
        //获取字段
        $field = CrmField::get_list();
        //分类
        $category = get_dict_list(13);
        $from = get_dict_list(14);
        $industry = get_dict_list(15);
        $status = CrmCustomer::get_status();
        $user = User::get_list();
        return $this->fetch('save', [
            'data'      => $data,
            'field'     => $field,
            'category'  => $category,
            'from'      => $from,
            'industry'  => $industry,
            'status'    => $status,
            'user'      => $user,
        ]);
    }

    /**
     * 删除用户
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
//            $data = CrmCustomer::with(['track','contract'])->find($param['id']);
//            $data->together(['track','contract'])->delete();
            CrmCustomer::destroy($param['id']);
            insert_user_log('删除客户');
            $this->success('删除成功');
        }
    }

    /**
     * 转移客户
     * @return mixed
     */
    public function transfer()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = CrmCustomer::where('id','in',$param['id'])->update(['user_id'=>$param['user_id']]);
            if ($result == true) {
                CrmTrack::insert_system_track($param['id'],0,'将客户转移给'.User::get_username($param['user_id']));
                insert_user_log('批量转移了个客户给客服');
                $this->success('批量转移了个客户给客服');
            } else {
                $this->error('转移不成功');
            }
        }

        return $this->fetch('save_transfer',[
            'user' => User::get_list()
        ]);
    }

    /**
     * 批量领取
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receive()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //检查是否有限制每日领取数量
            $data = crm_setting('crm');
            if(isset($data['pool_drawnum']) && $data['pool_drawnum'] > 0){
                //统计今日领取了多少
                $count = CrmCustomer::whereDay('draw_time')->count();
                if($data['pool_drawnum'] < $count+count($param['id'])){
                    $this->success('您今日已领取'.$count.'个客户,还可以领取'.($data['pool_drawnum']-$count).'个客户');
                }

            }
            \app\common\model\CrmCustomer::where('id','in',$param['id'])->update(['user_id'=>UserId(),'draw_time'=>time()]);
            //CrmTrack::insert_system_track($param['id'],0,User::get_username(UserId()).'领取了客户');
            insert_user_log('批量领取了'.count($param['id']).'个客户');
            $this->success('批量领取了'.count($param['id']).'个客户');
        }
    }

    /**
     * 批量客户转入公海
     */
    public function transfer_pool()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = CrmCustomer::where('id','in',$param['id'])->update(['user_id'=>0,'draw_time'=>0]);
            //CrmTrack::insert_system_track($param['id'],0,User::get_username(UserId()).'领取了客户');
            insert_user_log('批量将'.count($param['id']).'个客户转入私海');
            $this->success('成功将'.count($param['id']).'个客户转入私海');

        }
    }

    /**
     * 客户导入
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function import()
    {
        if ($this->request->isPost()) {
            try {
                $file = request()->file('file');
                $import_path = \think\facade\Filesystem::disk('public')->putFile('uploads/store_'.StoreId(),$file);
                $spreadsheet = IOFactory::load($import_path);
                $sheet = $spreadsheet->getActiveSheet();
                $sheetData = $sheet->toArray();
                if(empty($sheetData) || !is_array($sheetData)){
                    $this->error('上传失败');
                }
                //开始录入
                foreach ($sheetData as $k=>$r)
                {
                    if(empty((array_filter($r))))
                    {
                        continue;
                    }
                    if($k>='1'){
                        $data[$k]['store_id'] = StoreId();
                        //判断的导入位置
                        $setting = crm_setting('crm');
                        if(isset($setting['pool_import']) && $setting['pool_import'] == 0){
                            $user_id = UserId();
                        }else{
                            $user_id = 0;
                        }
                        $data[$k]['user_id'] = $user_id;
                        $data[$k]['company'] = $sheetData[$k][0];
                        $data[$k]['name'] = $sheetData[$k][1];
                        $data[$k]['mobile'] = $sheetData[$k][2];
                        $data[$k]['wechat'] = $sheetData[$k][3];
                        $data[$k]['email'] = $sheetData[$k][4];
                        $data[$k]['phone'] = $sheetData[$k][5];
                        $data[$k]['province'] = $sheetData[$k][6];
                        $data[$k]['city'] = $sheetData[$k][7];
                        $data[$k]['region'] = $sheetData[$k][8];
                        $data[$k]['address'] = $sheetData[$k][9];
                        $data[$k]['birthday'] = $sheetData[$k][10];
                        $data[$k]['category_id'] = DictData::get_dictid($sheetData[$k][11]);
                        $data[$k]['from_id'] = DictData::get_dictid($sheetData[$k][12]);
                        $data[$k]['industry_id'] = DictData::get_dictid($sheetData[$k][13]);
                        $data[$k]['status'] = $sheetData[$k][14];
                        $data[$k]['remark'] = $sheetData[$k][15];
                        $data[$k]['create_time'] = $data[$k]['update_time'] = time();
                    }
                }
                $result = CrmCustomer::insertAll($data);
                $this->success('成功导入'.count($data).'条数据');

            } catch (\think\exception\ValidateException $e) {
                $this->error($e->getMessage());
            }
        }

        return $this->fetch('import');
    }
    /**
     * 公海客户
     * @return mixed
     */
    public function pool()
    {
        //获取字段
        $field = CrmField::get_list();
        return $this->fetch('pool',[
            'field'  => $field
        ]);
    }
    public function pool_json($limit='15')
    {
        $model = new \app\common\model\CrmCustomer();
        $list = $model->with(['user','category','from','industry'])->order('sort_order desc,id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail($id,$show='track')
    {
        //获取字段
        $data = CrmCustomer::with(['user','category','from','industry'])->where('id',$id)->find()?:$this->error('参数错误');
        //获取字段
        $field = CrmField::get_list();
        //回访
        $track = CrmTrack::with(['user','customer'])->where('customer_id',$id)->order('create_time desc,id desc')->select();
        //合同
        $contract = CrmContract::with(['user','customer'])->where('customer_id',$id)->order('create_time desc,id desc')->select();
        //通知
        $notice = Notice::with(['user','customer'])->where('customer_id',$id)->order('status asc,datetime asc,id desc')->select();

        return $this->fetch('detail',[
            'data'     => $data,
            'show'     => $show,
            'field'    => $field,
            'track'    => $track,
            'contract' => $contract,
            'notice'   => $notice,
        ]);
    }



}